﻿Imports System.Xml.Serialization
Imports System.IO

''' <summary>
''' シリアライザー
''' </summary>
''' <typeparam name="T"></typeparam>
''' <remarks></remarks>
Public MustInherit Class Serializer(Of T)

    ''' <summary>
    ''' シリアル化します
    ''' </summary>
    ''' <param name="path"></param>
    ''' <remarks></remarks>
    Public Sub Serialize(ByVal path As String)
        Dim sr As New XmlSerializer(Me.GetType)
        Dim fs As FileStream = Nothing

        Try
            fs = New System.IO.FileStream(path, IO.FileMode.Create)
            Using wr As New System.IO.StreamWriter(fs)
                fs = Nothing
                sr.Serialize(wr, Me)
            End Using
        Finally
            If fs IsNot Nothing Then fs.Dispose()
        End Try
    End Sub
End Class

''' <summary>
''' シリアライザー
''' </summary>
''' <remarks></remarks>
Public NotInheritable Class Serializer
    Private Sub New()
    End Sub

    ''' <summary>
    ''' 逆シリアル化します
    ''' </summary>
    ''' <param name="path"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function Deserialize(Of T)(ByVal path As String) As T
        Dim sr As New XmlSerializer(GetType(T))
        Dim fs As FileStream = Nothing

        Try
            fs = New System.IO.FileStream(path, IO.FileMode.Open)
            Using r As New System.IO.StreamReader(fs)
                fs = Nothing
                Return DirectCast(sr.Deserialize(r), T)
            End Using
        Finally
            If fs IsNot Nothing Then fs.Dispose()
        End Try
    End Function
End Class